﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CustomImage.cs" company="Sitecore">
//   Alexander Doroshenko
// </copyright>
// <summary>
//   Defines the image with placeholder class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Sitecore.SharedSource.ImagePlaceholder
{
  using System.Text.RegularExpressions;
  using System.Web.UI;
  using Sitecore.Configuration;
  using Sitecore.Data.Items;
  using Sitecore.Globalization;
  using Sitecore.Shell.Applications.ContentEditor;
  using Sitecore.StringExtensions;

  /// <summary>
  /// Defines the image with placeholder class.
  /// </summary>
  public class CustomImage : Image
  {
    /// <summary>
    /// Gets or sets the field ID.
    /// </summary>
    /// <value>
    /// The field ID.
    /// </value>
    public string FieldID { get; set; }

    /// <summary>
    /// Gets the dimensions.
    /// </summary>
    /// <param name="title">The title.</param>
    /// <returns>
    /// The dimensions.
    /// </returns>
    public static string GetDimensions(string title)
    {
      var pattern = Settings.GetSetting("Sitecore.SharedSource.ImagePlaceholder.Pattern", @"(\d+)x(\d+)");
      var regex = new Regex(pattern, RegexOptions.IgnoreCase);
      var match = regex.Match(title);
      if (!match.Success)
      {
        return string.Empty;
      }

      return match.Groups[0].Value;
    }

    /// <summary>
    /// Executes the render event.
    /// </summary>
    /// <param name="output">The output.</param>
    protected override void DoRender(HtmlTextWriter output)
    {
      Diagnostics.Assert.ArgumentNotNull(output, "output");
      Item mediaItem = this.GetMediaItem();

      if ((mediaItem == null) && Settings.GetBoolSetting("Sitecore.SharedSource.ImagePlaceholder.Enabled", false))
      {
        var fieldItem = Sitecore.Context.ContentDatabase.GetItem(this.FieldID);
        if (fieldItem == null)
        {
          return;
        }

        var dimensions = GetDimensions(fieldItem["Title"]);
        if (string.IsNullOrEmpty(dimensions))
        {
          base.DoRender(output);
          return;
        }

        output.Write("<div id=\"" + this.ID + "_pane\" class=\"scContentControlImagePane\">");
        string clientEvent = Sitecore.Context.ClientPage.GetClientEvent(this.ID + ".Browse");

        var serviceUrl = Settings.GetSetting("Sitecore.SharedSource.ImagePlaceholder.ServiceUrl", "http://www.placehold.it/{0}/{1}/{2}").FormatWith(
          dimensions, 
          Settings.GetSetting("Sitecore.SharedSource.ImagePlaceholder.BackgroundColor", "CCCCCC"), 
          Settings.GetSetting("Sitecore.SharedSource.ImagePlaceholder.FontColor", "969696"));

        output.Write("<div class=\"scContentControlImageImage\" onclick=\"" + clientEvent + "\">");
        output.Write(string.Concat(new string[]
	    {
		    "<iframe",
		    " id=\"" + this.ID + "_image\"",
		    " src=\"" + serviceUrl + "\"",
		    " alt=\"" + string.Empty + "\"",
		    " frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" width=\"100%\" height=\"128\" allowtransparency=\"allowtransparency\"></iframe>"
	    }));
        // output.Write("<img src=\"{0}\" style=\"float: left; max-height: 128px; min-height: 100px;\">".FormatWith(serviceUrl));
        output.Write("</div>");
        output.Write("<div id=\"" + this.ID + "_details\" class=\"scContentControlImageDetails\">");
        output.Write("</div>");
        output.Write("</div>");
      }
      else
      {
        base.DoRender(output);
      }
    }

    /// <summary>
    /// Gets the media item.
    /// </summary>
    /// <returns>
    /// The media item.
    /// </returns>
    private Item GetMediaItem()
    {
      string attribute = this.XmlValue.GetAttribute("mediaid");
      if (attribute.Length > 0)
      {
        Language language = Language.Parse(this.ItemLanguage);
        return Client.ContentDatabase.GetItem(attribute, language);
      }

      return null;
    }
  }
}
